const { resolve } = require('path')

// gzip压缩
const CompressionWebpackPlugin = require('compression-webpack-plugin')

// 代码压缩
const TerserPlugin = require('terser-webpack-plugin')


module.exports = {
  publicPath: './',
  outputDir: 'dist',
  assetsDir: 'static',
  // 如果你不需要使用eslint，把lintOnSave设为false即可
  lintOnSave: false,
  productionSourceMap: process.env.NODE_ENV !== 'production',
  // 跨域代理
  devServer: {
	open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    progress: true,
	// 	proxy: {
	// 		'/api': {
	// 			target: process.env.VUE_APP_BASE_API,
	// 			changeOrigin: true,  // needed for virtual hosted sites
  //      ws: true, // proxy websockets
  //      pathRewrite: {
  //        '^/api': ''
  //      }
	// 		}
	// 	}
	},
  configureWebpack: () => {
    process.env.NODE_ENV === 'development' ? 'source-map' : undefined
  },
  css: {
    loaderOptions: {
      sass: {
        prependData: `
          @import "@/style/variables.scss";
        `
      }
    }
  },
  chainWebpack: config => {
    config.resolve.alias.set('vue-i18n', 'vue-i18n/dist/vue-i18n.cjs.js')
    // 防止多页面打包卡顿
    config.plugins.delete('named-chunks')

    // 修复HMR(热更新)
    config.resolve.symlinks(true)

    config.resolve.alias.set('@', resolve('src'))

    // 设置svg-loader
    // 在已有的svg loader配置中 排除掉对src/icons里svg进行转换
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons')) // 排除掉src/icons目录
      .end()
    // svg icon工作原理 https://segmentfault.com/a/1190000015367490
    // 配置svg-sprite-loader
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons')) // 指定src/icons要处理svg的文件目录
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader') // 用svg-sprite-loader解析
      .options({
        symbolId: 'icon-[name]' // symbol id命名格式 icon-图标名称
      })
      .end()
    
    // 图片压缩
    config.module
      .rule('images')
      .use('image-webpack-loader')
      .loader('image-webpack-loader')
      .options({
        bypassOnDebug: true
      })
      .end()

    // 生产环境
    config.when(process.env.NODE_ENV === 'production', config => {
        // gzip压缩
        const productionGzipExtensions = ['html', 'js', 'css']
        config.plugin('CompressionWebpackPlugin')
          .use(new CompressionWebpackPlugin({
            filename: '[path].gz[query]',
            algorithm: 'gzip',
            test: new RegExp(
              '\\.(' + productionGzipExtensions.join('|') + ')$'
            ),
            threshold: 10240, // 只有大小大于该值的资源会被处理 10240
            minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
            deleteOriginalAssets: false // 删除原文件
          }))

        config.plugin('TerserPlugin')
          .use(new TerserPlugin({
            terserOptions: {
              // 生产环境自动删除console
              compress: {
                drop_debugger: true,
                drop_console: true,
                pure_funcs: ['console.log']
              }
            },
            sourceMap: false,
            parallel: true
          }))
        
        config.plugin('ScriptExtHtmlWebpackPlugin')
          .after(`html`)
          .use('script-ext-html-webpack-plugin', [{
            inline: /runtime\..*\.js$/
          }])
          .end()

        config.optimization.splitChunks({
            chunks: 'all',
            cacheGroups: {
              libs: {
                name: 'chunk-libs',
                test: /[\\/]node_modules[\\/]/,
                priority: 10,
                chunks: 'initial'
              },
              element: {
                name: 'chunk-element', // 拆分element-plus
                priority: 20, // 权重
                test: /[\\/]node_modules[\\/]_?element-plus(.*)/
              },
              commons: {
                name: 'chunk-commons',
                test: resolve('src/components'),
                minChunks: 3, // 最小使用数
                priority: 5,
                reuseExistingChunk: true
              }
            }
          })

        config.optimization.runtimeChunk('single')
    })
  },
}